package de.dhbw.vs.permachat.client;

import com.google.gwt.place.shared.Place;
import com.google.gwt.user.client.History;
import com.google.web.bindery.event.shared.EventBus;
import com.google.web.bindery.event.shared.HandlerRegistration;
import com.googlecode.mgwt.dom.client.event.mouse.HandlerRegistrationCollection;
import com.googlecode.mgwt.mvp.client.history.HistoryHandler;
import com.googlecode.mgwt.mvp.client.history.HistoryObserver;

import de.dhbw.vs.permachat.client.activities.chat.ChatPlace;
import de.dhbw.vs.permachat.client.activities.chatroomlist.ChatRoomListPlace;
import de.dhbw.vs.permachat.client.activities.chatroomlist.ChatRoomSelectedEvent;
import de.dhbw.vs.permachat.client.activities.login.LoggedInEvent;
import de.dhbw.vs.permachat.client.activities.login.LoginPlace;
import de.dhbw.vs.permachat.client.dto.ChatRoom;

public class AppHistoryObserver implements HistoryObserver {

	@Override
	public void onPlaceChange(Place place, HistoryHandler handler) {

	}

	@Override
	public void onHistoryChanged(Place place, HistoryHandler handler) {

	}

	@Override
	public void onAppStarted(Place place, HistoryHandler historyHandler) {
		historyHandler.replaceCurrentPlace(new LoginPlace());
	}

	@Override
	public HandlerRegistration bind(EventBus eventBus,
			final HistoryHandler historyHandler) {

		HandlerRegistration chatRoomSelectedHandlerReg = eventBus.addHandler(
				ChatRoomSelectedEvent.getType(),
				new ChatRoomSelectedEvent.Handler() {

					@Override
					public void onChatRoomSelected(ChatRoomSelectedEvent event) {

						ChatRoom chatRoom = event.getChatRoom();
						historyHandler.goTo(new ChatPlace(chatRoom));

					}
				});

		HandlerRegistration loggedInHandlerReg = eventBus.addHandler(
				LoggedInEvent.getType(),
				new LoggedInEvent.Handler() {

					@Override
					public void onLoggedIn(LoggedInEvent event) {
						historyHandler.goTo(new ChatRoomListPlace());
					}
				});

		HandlerRegistration backHandlerReg = ActionEvent.register(eventBus,
				ActionNames.BACK, new ActionEvent.Handler() {

					@Override
					public void onAction(ActionEvent event) {

						History.back();

					}
				});

		HandlerRegistration animationEndHandlerReg = ActionEvent.register(eventBus,
				ActionNames.ANIMATION_END, new ActionEvent.Handler() {

					@Override
					public void onAction(ActionEvent event) {
						History.back();
					}
				});

		HandlerRegistrationCollection col = new HandlerRegistrationCollection();
		col.addHandlerRegistration(animationEndHandlerReg);
		col.addHandlerRegistration(backHandlerReg);
		col.addHandlerRegistration(chatRoomSelectedHandlerReg);
		col.addHandlerRegistration(loggedInHandlerReg);
		return col;
	}
}
